import Vue from 'vue'
import VueRouter from 'vue-router'
import store from "../store"


Vue.use(VueRouter)



// 导出数据给menu的form.vue
export const IndexRoutes = [
  {
    path: "menu",
    component: () => import("../pages/menu/menu.vue"), meta: { title: "菜单管理" },
    // beforeEnter(to, from, next) {
    //   // 取出用户可以访问的所有路由
    //   let { userInfo: { menus_url } } = store.getters;
    //   // 判断是否包含当前路由，包含，next(),不包含，去首页
    //   if(menus_url.includes('/menu')){
    //     next()
    //   }else{
    //     next("/")
    //   }
    // }
  },
  {
    path: "role",
    component: () => import("../pages/role/role.vue"), meta: { title: "角色管理" }
  },
  {
    path: "manage",
    component: () => import("../pages/manage/manage.vue"), meta: { title: "管理员管理" }
  },
  {
    path: "cate",
    component: () => import("../pages/cate/cate.vue"), meta: { title: "商品分类" }
  },
  {
    path: "specs",
    component: () => import("../pages/specs/specs.vue"), meta: { title: "商品规格" }
  },
  {
    path: "goods",
    component: () => import("../pages/goods/goods.vue"), meta: { title: "商品管理" }
  },
  {
    path: "banner",
    component: () => import("../pages/banner/banner.vue"), meta: { title: "轮播图管理" }
  },
  {
    path: "member",
    component: () => import("../pages/member/member.vue"), meta: { title: "会员管理" }
  }, {
    path: "seckill",
    component: () => import("../pages/seckill/seckill.vue"), meta: { title: "秒杀活动" }
  },
]
//给每条路由添加路由独享 守卫，再放入路由规则(routes)中
IndexRoutes.forEach(item => {
  item.beforeEnter = (to, from, next) => {
    // 取出用户可以访问的所有路由
    let { userInfo: { menus_url } } = store.getters;
    // 判断是否包含当前路由，包含，next(),不包含，去首页
    if (menus_url.includes('/'+item.path)) {
      next()
    } else {
      next("/")
    }
  }
})

const routes = [
  {
    path: "/login",
    component: () => import("../pages/login/login.vue")
  },
  {
    path: "/",
    component: () => import("../pages/index/index.vue"),
    children: [
      {
        path: "",
        component: () => import("../pages/home/home.vue"),
      },
      ...IndexRoutes
    ]
  },
  // {
  //   path: "*",
  //   redirect: "/home"
  // }
]


const router = new VueRouter({
  routes
})


//登录拦截 
router.beforeEach((to, from, next) => {
  // 1.如果去的是登录，直接next 
  if (to.path === "/login") {
    next()
    return;
  }
  // 2.如果不是登录，判断是否登录（判断vuex中的userInfo.token），登录了，就next 
  if (store.getters.userInfo.token) {
    next()
    return
  }
  // 3.未登录，next('/login')
  next("/login")
})

export default router
